<template>
  <el-dialog
    modal-class="merak_modal"
    v-model="dialogTariffTemplate"
    direction="rtl"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="600"
    :before-close="drawerClose"
  >
    <template #header>
      <div class="merak_modal_title">{{$t('goods_tariff.export_templete')}}</div>
    </template>
    <div v-loading="loadingTariff">
      <div class="line_item">
        <span class="num_span"><el-icon><Download /></el-icon></span
        ><span class="down_template" @click="downTemplate">
           {{$t('goods_tariff.down_tariff_template')}}
        </span>
      </div>
     
      <div class="upload_class">
        <el-upload class="upload-demo" drag action="#" accept=".xls,.xlsx" :multiple="false" :show-file-list="false" :http-request="handleRequestInfo">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text"> {{ $t("merak.push_fil_tip") }} <em>{{ $t("merak.click_upload") }}</em></div>
          <template #tip>
            <div class="el-upload__tip">{{$t('goods_tariff.template_tip')}}</div>
          </template>
        </el-upload>

        <div class="uploadErr" v-if="errKey">当前上传文件有失败数据，<span class="err_tip" @click="downErrData">点击下载</span></div>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, getCurrentInstance, nextTick } from "vue";
import uploadFile from "@/components/uploadFileMerak/index.vue";
import { downTempleteApi,downFailTempleteApi, Path } from "@/api/modules/goodsArchive/tariff/tariff";
import { uploadFiles } from "@/api/modules/upload";

import { successMsg, failMsg, confirmWarningMsg, warnMsg } from "@/utils/messageUtils";
const props = withDefaults(
  defineProps<{
    dialogTariff?: boolean;
    typeId: string;
  }>(),
  {}
);

const dialogTariffTemplate = ref(false);
watch(
  () => props.dialogTariff,
  newValue => {
    dialogTariffTemplate.value = newValue;
  }
);

const loadingTariff=ref(false);
const uploadRef = ref(null);

const uploadProps = reactive({
  params: {},
  uploadLoading: true,
  listType: "picture-card",
  uploadClass: "picUpload",
  accept: ".xls,.xlsx",
  fileListShow: false,
  tipShow: false,
  path: Path.tariffUpload
});

watch(
  () => props.typeId,
  (newValue, oldValue) => {
    uploadProps.params = { type_id: props.typeId };
  }
);

const errKey=ref("");//错误key
const downTemplate = () => {
  downTempleteApi({ type_id: props.typeId }).then(res => {
  
    let a = document.createElement("a");
    //ArrayBuffer 转为 Blob
    let blob = new Blob([res], { type: "application/vnd.ms-excel" });

    let objectUrl = URL.createObjectURL(blob);
    a.setAttribute("href", objectUrl);
    a.setAttribute("download", Date.now().toString() + ".xlsx");
    a.click();
  });
};

const handleRequestInfo = async (options, type) => {
  // console.log("发送请求。。。。");
   errKey.value="";
  loadingTariff.value=true;
  const formData = new FormData();
  let file = options.file;

  formData.append(options.filename, file);

  let paramsObj = { type_id: props.typeId };
    console.log(Path.tariffUpload)
  uploadFiles(Path.tariffUpload, paramsObj, formData, evt => {
    // console.log(evt);
    options.onProgress(evt);
  })
    .then(({ code, data, message }) => {
        loadingTariff.value=false;

      if (code == ResultEnum.SUCCESS) {
        // console.log(data);
        // console.log("成功。。。。。。。。。");
        successMsg("上传成功.");
         $emit("drawerCloseDialog",{type:'refresh'});

      } else if(code=="5010") { 
        errKey.value=message.key;
      }else{
        failMsg(message)
      }
    })
    .catch(err => {
        loadingTariff.value=false;
     
    });
};



const downErrData=()=>{
    downFailTempleteApi({key:errKey.value}).then(res => {
  
    let a = document.createElement("a");
    //ArrayBuffer 转为 Blob
    let blob = new Blob([res], { type: "application/vnd.ms-excel" });

    let objectUrl = URL.createObjectURL(blob);
    a.setAttribute("href", objectUrl);
    a.setAttribute("download", Date.now().toString() + ".xlsx");
    a.click();
  });
}
const drawerClose = () => {
  $emit("drawerCloseDialog",{});
};

onMounted(() => {
  uploadRef.value?.readMe();
});

const $emit = defineEmits<{
  drawerCloseDialog: any;
}>();
</script>
<style lang="scss" scoped>
:deep(.el-upload-dragger .el-icon--upload) {
  font-size: 32px;
}
.line_item {
      display: flex;
    align-items: center;
    padding: 10px 20px;
    border-radius: 2px;
    border: 1px solid #d8d8d8;
    box-shadow: 0px 0px 5px 3px #ebebeba3;
    margin-bottom: 20px;
    cursor: pointer;
  .num_span {
       border: 1px solid #7c8089;
    font-size: 14px;
    border-radius: 50%;
    padding: 4px 5px 1px 5px;
  }
  .down_template {
   margin-left: 10px;
    font-size: 14px;
    color: #7c8089;
  }
}
.upload_class {
   padding: 20px 20px;
     border: 1px solid #d8d8d8;
    box-shadow: 0px 0px 5px 3px #ebebeba3;
    margin-bottom: 20px;
    border-radius: 2px;
}
.uploadErr{
    font-size: 14px;
    padding-top: 10px;
    .err_tip{
        color: red;
        cursor: pointer;
    }
}
</style>
